package net.shopxx.action.admin;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.jsp.PageContext;

import net.shopxx.bean.Pager;
import net.shopxx.entity.Product;
import net.shopxx.entity.Product.VerifyStatus;
import net.shopxx.service.HtmlService;
import net.shopxx.service.ProductService;

import org.apache.struts2.convention.annotation.ParentPackage;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.oscache.base.Cache;
import com.opensymphony.oscache.web.ServletCacheAdministrator;

/**
 * 后台Action类 - 商品
 */

@ParentPackage("admin")
public class ProductAction extends BaseAdminAction {

	private static final long serialVersionUID = -4433964283757192334L;

	private Product product;

	@Resource
	private ProductService productService;
	@Resource
	private HtmlService htmlService;

	// 列表
	public String list() {
		// pager = productService.findByPager(pager);
		if (pager == null) {
			pager = new Pager();
		}
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(Product.class);
		detachedCriteria.add(Restrictions.eq("isMarketable", false));
		detachedCriteria
				.add(Restrictions.eq("verifyStatus", VerifyStatus.wait));
		pager = productService.findByPager(pager, detachedCriteria);
		return LIST;
	}

	// 验证请求
	public String verify() throws Exception {
		for (String id : ids) {
			Product product = productService.load(id);
			product.setVerifyStatus(VerifyStatus.pass);
			productService.update(product);
		}
		flushCache();
		return ajaxJsonSuccessMessage("操作成功");
	}

	public String rejectverify() throws Exception {
		for (String id : ids) {
			Product product = productService.load(id);
			product.setVerifyStatus(VerifyStatus.nopass);
			productService.update(product);
		}
		flushCache();
		return ajaxJsonSuccessMessage("操作成功");
	}

	public String preview() throws Exception {
		product = productService.load(id);
		htmlService.productContentBuildHtml(product);
		
		getResponse().sendRedirect(getRequest().getContextPath()+"/"+product.getHtmlFilePath());
		return null;
	}

	// 更新页面缓存
	private void flushCache() {
		Cache cache = ServletCacheAdministrator.getInstance(
				getRequest().getSession().getServletContext()).getCache(
				getRequest(), PageContext.APPLICATION_SCOPE);
		cache.flushAll(new Date());
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

}